/**
 * 
 */
package com.videoshare.user;

/**
 * @author Administrator
 *
 */
import javax.servlet.http.*;

import org.apache.struts.action.*;
import org.apache.commons.logging.*;

import com.sapientia.user.UserConstants;
import com.sapientia.user.bean.*;
import com.sapientia.user.dao.*;

import java.util.*;
import java.sql.*;

import javax.sql.*;

public class UserLoginAction extends Action 
{
	private static Log log = LogFactory.getLog(UserLoginAction.class);
	
	public ActionForward execute(
			ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,
			HttpServletResponse response) throws Exception
	{
		UserLoginForm userForm = (UserLoginForm)form;
		
		
		// ---------------put business logic here-----------
		Connection conn = getDataSource(request,"userDB").getConnection();
		DAOFactory factory = new DAOFactory(); 
		UserDAO dao = factory.createUserDAO(conn);
		boolean isUser = false;
		try{
			isUser = dao.checkUser(userForm);
			
		}
		finally{
				conn.close();
		}
		
		//--------------------------------------------------
		
		
		log.trace("In execute(..) method of UserLoginAction");
		
		
		// business logic worked out well 
		if( isUser )
		{
			HttpSession session = request.getSession();
			//mette l'utente in session per verifica durante la richiesta della clip
			userForm.setLoggedIn(true);
			session.setAttribute(UserConstants.USER_KEY,userForm);
			return mapping.findForward("success");
		}
		else
		{	
			// invalid user name and/or password
			ActionMessages errors = new ActionMessages();
			errors.add(
                    ActionMessages.GLOBAL_MESSAGE,
                    new ActionMessage("userLogin.failure.message"));
			this.saveErrors(request, errors);
			// try to log in again
			return mapping.getInputForward();
		}
		
		
	}


}
